/**
 * Created by python on 18-10-2.
 */

function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

$(function(){
    $("#myform").submit(function (e) {
        e.preventDefault()

        // TODO 增加分类提交
        var params = {};
        // 获取到所有的参数
        $(this).serializeArray().map(function (x) {
            params[x.name] = x.value;
        });
        // 取到参数以便判断
        var category_name = params["category_name"];
        var content = params["content"];


        params = {
            "category_name": category_name,
            "content": content
        };
        $.ajax({
            url: "/admin/add_category",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(params),
            success: function (resp) {
                if (resp.errno == "0") {
                    // 返回上一页，刷新数据
                    alert("添加成功")
                    location.href = document.referrer;
                }else {
                    alert(resp.errmsg);
                }
            }
        })
    })

    $("#alter_form").submit(function (e) {
        e.preventDefault()

        // TODO 修改分类提交
        var params = {};
        // 获取到所有的参数
        $(this).serializeArray().map(function (x) {
            params[x.name] = x.value;
        });
        // 取到参数以便判断
        var category_name = params["category_name"];
        var content = params["content"];

        params = {
            "category_name": category_name,
            "content": content
        };
        $.ajax({
            url: "/admin/alter_category",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(params),
            success: function (resp) {
                if (resp.errno == "0") {
                    // 返回上一页，刷新数据
                    alert("修改成功")
                    location.href = document.referrer;
                }else {
                    alert(resp.errmsg);
                }
            }
        })
    })


    $(".link-del").click(function (e) {
        var category_id  = $(this).attr("category_id")
        $.get('/admin/del_category/'+category_id,function (resp) {
            if (resp.errno == "0") {
                location.reload()
            }else {
                alert(resp.errmsg)
            }
        })

    })

});




